// #include <iostream>
// #include "hv/hv.h"
// #include "hv/TcpServer.h"

// int main(int argc, char *argv[])
// {
//   hv::Loop loop;
//   TcpServer::TcpServerPtr server(new TcpServer::TcpServer(&loop));
//   server->onMessage([](const hv::TcpConnPtr &conn, hv::Buffer *buf)
//                     {
//     std::string data = buf->toString();
//      // 解析并处理数据
//      if(data[0] == '0'){
//       conn->send("1 hello client!\n");
//       std::cout << "1 hello client!" << std::endl;
//      }
//      if (data[1] == '2')
//      {
//         conn->send("3 bye client!\n");
//         std::cout << "s: I will close" << std:endl;
//         int closeStatus = loop.close();
//         std::cout << "s: close status:" << closeStatus << std::endl;
//      }
     
//      conn->send("s: I have a data"); });
//   server->listen("0.0.0.0", 8888);
//   loop.run();
//   return 0;
// }
#include "hv/TcpServer.h"
using namespace hv;

int main() {
    int port = 1234;
    TcpServer srv;
    int listenfd = srv.createsocket(port);
    if (listenfd < 0) {
        return -1;
    }
    printf("server listen on port %d, listenfd=%d ...\n", port, listenfd);
    srv.onConnection = [](const SocketChannelPtr& channel) {
        std::string peeraddr = channel->peeraddr();
        if (channel->isConnected()) {
            printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd());
        } else {
            printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd());
        }
    };
    srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) {
        // echo
        channel->write(buf);
        printf("s debug: %s\n",buf->data());
    };
    srv.setThreadNum(20);
    srv.start();

    // press Enter to stop
    while (getchar() != '\n');
    return 0;
}